package lib.control;

import lib.JBierSubAdapter;
import lib.api.bierdopje.model.JBierEpisode;
import lib.api.bierdopje.model.JBierShow;
import lib.exception.VideoControlException;
import lib.logging.Logger;
import lib.model.EpisodeFile;
import lib.model.Subtitle;
import settings.model.MappingBierdopjeScene;

import java.util.ArrayList;
import java.util.List;

public class EpisodeFileControl extends VideoFileControl {

	private final JBierSubAdapter jbs;

	public EpisodeFileControl(EpisodeFile episodeFile) {
		super(episodeFile);
		jbs = new JBierSubAdapter();
	}

	public EpisodeFile process(List<MappingBierdopjeScene> dict)
			throws VideoControlException {
		Logger.instance.trace("EpisodeFileControl", "process", "");
		EpisodeFile episodeFile = (EpisodeFile) videoFile;
		if (episodeFile.getShow().equals("")) {
			throw new VideoControlException(
					"Unable to extract episode details, check file", videoFile);
		} else {
			Logger.instance.debug("Showname: " + episodeFile.getShow());
			JBierShow bshow = jbs.searchShow(episodeFile, dict);
			if (bshow != null) {
				episodeFile.updateBierShowInfo(bshow);
				JBierEpisode bepisode = jbs.searchEpisode(episodeFile);
				if (bepisode != null) {
					episodeFile.updateBierEpisodeInfo(bepisode);
				} else {
					throw new VideoControlException("Season "
							+ episodeFile.getSeason() + " Episode "
							+ episodeFile.getEpisodeNumbers().toString()
							+ "not found, check file", videoFile);
				}
			} else {
				throw new VideoControlException("Show not found, check file",
						videoFile);
			}
			return episodeFile;
		}
	}

	public EpisodeFile processWithSubtitles(List<MappingBierdopjeScene> dict,
			String languageCode, boolean exactMatch)
			throws VideoControlException {
		Logger.instance.trace("EpisodeFileControl", "processWithSubtitles", "");
		EpisodeFile episode = process(dict);
		if (episode != null) {
			List<Subtitle> listFoundSubtitles = new ArrayList<Subtitle>();
			//if ((languageCode.equalsIgnoreCase("nl") && episode
			//		.getBierEpisode().isSubsnl())
			//		|| (languageCode.equalsIgnoreCase("en") && episode
			//				.getBierEpisode().isSubsen())) {
				listFoundSubtitles.addAll(sc.getSubtitles(episode, exactMatch,
						languageCode));
				episode.setMatchingSubs(listFoundSubtitles);
			//}else{
				//to see if they havent been released in the last day
			//	listFoundSubtitles.addAll(sc.getSubtitlesRSS(episode, exactMatch, languageCode));
			//}
		}
		return episode;
	}

}
